<template>
  <div class="Breadcrumb">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/' }"
        ><el-button type="primary">文件管理</el-button></el-breadcrumb-item
      >
      <el-breadcrumb-item>
        <a href="/"><el-button type="primary" plain>文件管理</el-button></a>
      </el-breadcrumb-item>
      <el-breadcrumb-item
        ><el-button type="primary" plain
          >文件管理</el-button
        ></el-breadcrumb-item
      >
      <el-breadcrumb-item
        ><el-button type="primary" plain
          >文件管理</el-button
        ></el-breadcrumb-item
      >
    </el-breadcrumb>
  </div>
  <div class="page" direction="vertical">
    <div class="page_header" cell-class-name="tr">
      <el-space>
        <el-button type="default" @click="refresh">刷新</el-button>
        <el-button type="primary" @click="handleAdd">新增</el-button>
        <el-button
          type="danger"
          :disabled="selectedIds.length <= 0"
          @click="handleDelete(selectedIds)"
          >删除</el-button
        >
      </el-space>
      <el-space>
        <el-input  v-model="keyWord" placeholder="搜索关键字" clearable></el-input>
        <el-button 
        type="primary" 
        @click="handleSearch">搜索</el-button>
      </el-space>
    </div>
    <!-- 表格 -->
    <div class="page_body">
      <el-table
        v-loading="loading"
        :data="rows"
        border
        :default-sort="{ prop: query.order, order: query.sort + 'ending' }"
        @selection-change="handleSelectionChange"
        @sort-change="SortChange"
      >
        <el-table-column prop="select" type="selection" />
        <el-table-column prop="name" label="名称" />
        <el-table-column prop="label" label="标识">
          <template #default="{ row }">
            <el-tag>{{ row.label }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" />
        <el-table-column prop="createTime" label="创建时间" sortable="custom" />
        <el-table-column prop="updateTime" label="更新时间" sortable="custom" />
        <el-table-column label="操作">
          <template #default="{ row }">
            <el-space>
              <el-button
                type="default"
                text
                bg
                size="small"
                @click="handleEdit(row)"
                >编辑</el-button
              >
              <el-button
                type="danger"
                size="small"
                @click="handleDelete([row.id])"
                >删除</el-button
              >
            </el-space>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="page_footer"
      style="display: flex; justify-content: end; padding-top: 15px"
    >
      <el-pagination
        v-model:current-page="query.page"
        v-model:page-size="query.size"
        :page-sizes="[5, 10, 15, 20]"
        background
        layout=" :total, sizes,  prev, pager, next, jumper"
        :total="total"
      />
    </div>
  </div>

  <el-dialog v-model="visible" :title="title" width="56%">
    <el-form ref="formRef" label-width="100" :model="model" :rules="rules">
      <el-row :gutter="25">
        <el-col :span="12">
          <el-form-item label="名称" prop="name">
            <el-input
              type="text"
              v-model="model.name"
              placeholder="请输入名称"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="标识" prop="label">
            <el-input
              type="text"
              v-model="model.label"
              placeholder="请输入标识"
            />
          </el-form-item>
        </el-col>
      </el-row>

      <el-form-item label="备注" prop="remark">
        <el-input
          type="textarea"
          v-model="model.remark"
          placeholder="请输入备注"
          rows="4"
        />
      </el-form-item>
      <el-form-item label="功能权限" prop="menuIdList">
        <!-- <el-input type="text" placeholder="请输入关键字进行过滤" /> -->
        <MenuCheck v-model="model.menuIdList" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="handleCancel">取消</el-button>
      <el-button type="success" :loading="confirmLoading" @click="handleConfirm"
        >保存</el-button
      >
    </template>
  </el-dialog>
</template>
<script>
import {
  getSysRolePage,
  addSysRole,
  updateSysRole,
  deleteSysRole,
} from "@/api/sys.js";
import MenuCheck from "@/components/menu-check/index.vue";
import { ElMessage, ElMessageBox } from "element-plus";
export default {
  name: "SysRole",
  data() {
    return {
      title: "新增",
      visible: false, // 显示条件
      selectedIds: [],
      confirmLoading: false, // 保存中
      loading: false, // 请求中
      keyWord: "",// 搜索关键字
      query: {
        page: 1,
        size: 5,
        sort: "asc",
        order: "updateTime",
      },
      total: 1, // 总条数
      rows: [],
      model: {
        id: undefined,
        name: "",
        label: "",
        remark: "",
        menuIdList: [],
        relevance: 0,
        departmentIdList: [],
      },
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" },
          { min: 2, max: 9, message: "长度在2~9个字符之间", trigger: "blur" },
        ],
        label: [
          { required: true, message: "标识不能为空", trigger: "blur" },
          { min: 2, max: 9, message: "长度在2~9个字符之间", trigger: "blur" },
        ],
      },
    };
  },
  components: {
    MenuCheck,
  },
  methods: {
    async refresh() {
      try {
        this.loading = true;
        const { list, pagination } = await getSysRolePage({
          ...this.query,
          keyWord: this.keyWord,
        });
        this.rows = list;
        this.total = pagination.total;
        this.loading = false;
        // console.log("data", data);
      } catch (error) {}
    },
    handleSearch() {
      this.query.page = 1;
      this.refresh(); 
    },
    handleSelectionChange(arr) {
      // console.log(" handleSelectionChange", arr);
      this.selectedIds = arr.map((item) => item.id);
    },
    SortChange( { order, prop }){
      // order - 排序方式 ascending - 升序 descending - 降序
      // prop - 排序字段
      this.query.sort = order === "ascending" ? "asc" : "desc";
    },

    // 新增按钮
    handleAdd() {
      this.title = "新增";
      this.visible = true;
      this.$nextTick(() => {
        // 表单重置下
        this.model.id = undefined;
        this.$refs.formRef.resetFields();
      });
    },

    // 编辑按钮
    handleEdit(row) {
      this.title = "编辑";
      // console.log("编辑", row);

      this.visible = true;
      this.$nextTick(() => {
        // 数据回填
        // this.model.id = row.id;
        // this.model.name = row.name;
        // this.model.label = row.label;
        // this.model.remark = row.remark;
        // this.model.menuIdList = row.menuIdList;
        // 上面代码优化
        // const keys = ['id', 'name', 'label', 'remark', 'menuIdList']
        const keys = Object.keys(this.model);
        const result = keys.reduce((result, key) => {
          result[key] = row[key];
          return result;
        }, {});

        Object.assign(this.model, result);
      });
    },

    // 删除按钮
    async handleDelete(ids) {
      try {
        // 弹窗确认
        await ElMessageBox.confirm(
          "此操作将永久删除选中数据，是否继续?",
          "提示",
          {
            confirmButtonText: "确认",
            cancelButtonText: "取消",
            type: "warning",
          }
        );
        await deleteSysRole({ ids })
          .then(() => {
            ElMessage({
              type: "success",
              message: "删除成功",
            });
          })
          .catch(() => {
            ElMessage({
              type: "info",
              message: "取消删除",
            });
          });
        this.refresh();
      } catch (error) {
        console.error(error);
      }
    },

    // 取消按钮
    handleCancel() {
      this.$refs.formRef.resetFields();
    },
    // 保存按钮
    async handleConfirm() {
      // Promise  element-ui自带的校验方法 Form Exposes
      try {
        // 表单校验
        await this.$refs.formRef.validate();

        this.confirmLoading = true;
        // 调用接口
        if (this.model.id) {
          // 更新
          await updateSysRole(this.model);
        } else {
          // 新增
          await addSysRole(this.model);
        }

        //新增成功
        ElMessage.success("保存成功");
        // 关闭弹窗
        this.visible = false;
        // 重新刷新表格数据
        this.refresh();
      } catch (error) {
        console.error(error);
      } finally {
        this.confirmLoading = false;
      }
    },
  },
  created() {
    this.refresh();
  },
  watch: {
    query: {
      handler() {
        this.refresh();
      },
      deep: true,
    }
  }
};
</script>
<style scoped>
.Breadcrumb {
  width: 100%;
  height: 50px;
  /* line-height: 60px; */
}

.page_header {
  display: flex;
  justify-content: space-between;
}
.page_body {
  margin-top: 15px;
}
.el-form {
  margin-right: 20px;
}
</style>
